import React from 'react';
import { useEffect, useState } from 'react';
import {Table,Button, Select, Drawer, Form, Input, Checkbox,Alert,Progress } from 'antd';
import ConfigForm  from '../component/configForm';
import momentTZ from 'moment-timezone';
import {ipcClient} from '../../../src/ipc/IpcClent';
import 'antd/dist/antd.less';

const ButtonGroup = Button.Group;
const { Search,TextArea } = Input;

export default ()=> {
  //列表项目
  const [projects , setProjects] = useState([]);
  const [projectsLoading,setProjectsLoading] = useState(false);
  const [projectUpdate , setProjectUpdate] = useState(false);
  //新建版本
  const [newVersionVisible , setNewVersionVisible] = useState(false);
  const [versionUpLoading,setVersionUpLoading] = useState(false);
  const [form] = Form.useForm();
  const [uploadPercent,setUploadPercent] = useState(0);

  //新建项目
  const [newProjectVisible , setNewProjectVisible] = useState(false);
  const [includeVersionFlag, setIncludeVersionFlag] = useState(false);
  const [projectLoading,setProjectLoading] = useState(false);
  const [projectError,setProjectError]= useState(false);
  const [projectErrorMsg,setProjectErrorMsg]= useState('');
  // 配置对话框
  const [configVisible , setConfigVisible] = useState(false);

  const [projectform] = Form.useForm();
  const [configForm] = Form.useForm();

  useEffect(()=>{
    setProjectsLoading(true);
    const timeZone = momentTZ.tz.guess();
    ipcClient.findAllProjects((res)=>{
      if(res && res.success){
        let projectList = [];
        for (let index = 0; index < res.data.length; index++) {
              const element = res.data[index];
              projectList.push({...element, 
                projectType: element.projectType === 1 ? "产品原型":"项目原型",
                createdAt : momentTZ(new Date(element.createdAt)).tz(timeZone).format("yyyy-MM-DD HH:mm:ss"),
                updatedAt : momentTZ(new Date(element.updatedAt)).tz(timeZone).format("yyyy-MM-DD HH:mm:ss")});
        }
        console.log(projectList,timeZone);
        setProjects(projectList);
      }else{

      }
      setProjectsLoading(false);
    });

  },[projectUpdate]);
  
  const openFolder = (e)=>{
    console.log(e);
    ipcClient.openFolder(null,(res)=>{
      const {canceled,filePaths} = res;
      if(!canceled){
        form.setFieldsValue({localPath:filePaths[0]});
        projectform.setFieldsValue({localPath:filePaths[0]});
      }
    });
  }
  const refresh = ()=>{
    setProjectUpdate(!projectUpdate);
  }
  const openWeb = (project,isList) => {
    console.log("add new version",project);
    ipcClient.openWeb(project,isList);
  }
  const addNewVersion = (project)=>{
    console.log("add new version",project);
    form.resetFields();
    form.setFieldsValue({ projectId: project.projectId ,projectName:project.projectName});
    setUploadPercent(0);
    setProjectErrorMsg("");
    setNewVersionVisible(true);
  }
  //更新版本
  const submitNewVersion = (version)=>{
    setVersionUpLoading(true);
    let newVersion = {projectId:version.projectId,changeList:version.changeLog,uploadDateTime: new Date(), localFolder :version.localPath};
    ipcClient.addNewVersion(newVersion,(res)=>{
      if(res && res.type ){
        setProjectErrorMsg(res.msg);
        setUploadPercent(parseInt(res.percent));
      }else if(res && res.success){
        console.log(res.data);
        form.resetFields();
        setProjectErrorMsg(res.data);
        setProjectError(false);
        onNewVersionClose();
      }else{
        setProjectErrorMsg(res.errMsg);
        setProjectError(true);
        setProjectUpdate(!projectUpdate);
       }
       setIncludeVersionFlag(false);
       console.log("add version callback:",res);
      });
  }
  const onNewVersionClose = ()=>{
    form.resetFields();
    setNewVersionVisible(false);
    setVersionUpLoading(false);
  }

  //项目表单
  const addNewProject = ()=>{
    projectform.resetFields();
    setNewProjectVisible(true);
  }
  const onNewProjectClose = ()=>{
    projectform.resetFields();
    setNewProjectVisible(false);
    setProjectLoading(false);
  }
  const onIncludeVersionChange = ({includeVersion})=>{
    console.log(includeVersion);
    if ( typeof includeVersion !== 'undefined')
        setIncludeVersionFlag(includeVersion);
  }
  //提交新项目
  const submitNewProject = async (project)=>{
    const {projectId,projectName,description,projectType,includeVersion,localPath,changeLog} = project;
    let newProject = {projectName:projectName,description:description,projectType:projectType};

    ipcClient.addNewProject(newProject,(result)=>{
      if(!result.success){
        setProjectErrorMsg(result.errMsg);
        setProjectError(true);
      }else{
        setProjectError(false);
        
        //项目添加正确
        if(includeVersion){
          //准备原型版本
          let newVersion = {projectId:result.data.projectId,changeList:changeLog,uploadDateTime: new Date(), localFolder :localPath};
          ipcClient.addNewVersion(newVersion,(res)=>{
            console.log("Add new version with new project",res);
             if(res && res.type ){
              setProjectErrorMsg(res.msg);
              setUploadPercent(parseInt(res.percent));
             }else if(res && res.success){
              setProjectError(false);
              setProjectUpdate(!projectUpdate);
              onNewProjectClose();
             }else{
              setProjectErrorMsg(res.errMsg);
              setProjectError(true);
              setProjectUpdate(!projectUpdate);
             }
             setIncludeVersionFlag(false);
          });
        }else{
          //不需要添加版本
          onNewProjectClose();
          setProjectUpdate(!projectUpdate);
        }
      }
    });
  }
  const openConfig = ()=>{
    setConfigVisible(true);
  }
  const onConfigClose = ()=>{
    setConfigVisible(false);
  }
  const columns = [
    {
      title: '项目名称',
      dataIndex: 'projectName',
    },
    {
      title: '分类',
      dataIndex: 'projectType',
    },
    {
      title: '项目说明',
      dataIndex: 'description',
    },
    {
      title: '最后更新时间',
      dataIndex: 'updatedAt',
    },
    {
      title: '操作',
      dataIndex:'action',
      render: (text, item)=>{
        return (<>
                <Button size='small' onClick={()=>{addNewVersion(item)}}>更新版本</Button> 
                { item.currentVersion != null ? <> <Button size='small' onClick={()=>{openWeb(item, 0)}} >查看原型</Button> <Button size='small' onClick={()=>{openWeb(item,1)}} >查看历史</Button> </>: "" }
                </> )
      }
    },
  ];
  return (
    <div>
      <ButtonGroup style={{float:'right'}}>
        <Button size='small' type='primary' onClick={addNewProject} >新建项目</Button> 
        <Button size='small' onClick={refresh}>刷新</Button>
        <Button size='small' onClick={openConfig}>配置</Button>
        </ButtonGroup>
      <Table columns={columns} size="small" dataSource={projects} loading={projectsLoading} rowKey={"projectId"}></Table>
      
    
    <Drawer title="更新版本"
        placement="right"
        width={720}
        closable={false}
        onClose={onNewVersionClose}
        visible={newVersionVisible}
        footer={
          <div
            style={{
              textAlign: 'right',
            }}
          >
            <Alert type='info' message={projectErrorMsg} showIcon />

            <Progress percent={uploadPercent} />
            <Button onClick={onNewVersionClose} style={{ marginRight: 8 }}>
              取消
            </Button>
            <Button onClick={()=>{form.submit()}} type="primary" loading={versionUpLoading}>
              上传原型
            </Button>
          </div>
        }
        >
        <Form form={form} layout="vertical" onFinish={submitNewVersion} >
          <Form.Item
              name="projectName"
              label="项目名称"
          >
            <Input readOnly={true} bordered={false} />
          </Form.Item>
            <Form.Item
                name="projectId"
                hidden={true}
                >
                <Input />
            </Form.Item>
            <Form.Item
                  name="localPath"
                  label="原型本地目录"
                  rules={[{ required: true, message: '请选择原型本地目录' }]}
                >
                  <Search  allowClear='true' placeholder="请选择目录" readOnly={true} onSearch={openFolder} enterButton='选择目录' />
                </Form.Item>
            <Form.Item
                  name="changeLog"
                  label="版本说明"
                  rules={[{ required: true, message: '请选输入版本说明' }]}
                >
                  <TextArea allowClear='true' showCount='true' placeholder="版本说明" />
                </Form.Item>
        </Form>
    </Drawer>
    
    <Drawer title="新建项目"
        placement="right"
        width={720}
        closable={false}
        onClose={onNewProjectClose}
        visible={newProjectVisible}
        footer={
          <div
            style={{
              textAlign: 'right',
            }}
          >
            <Alert type='info' message={projectErrorMsg} showIcon />
            <Progress percent={uploadPercent} />
            <Button onClick={onNewProjectClose} style={{ marginRight: 8 }}>
              取消
            </Button>
            <Button onClick={()=>{projectform.submit()}} type="primary" loading={projectLoading}>
              新建项目
            </Button>
          </div>
        }
        >
        {projectError ? <Alert type='error' message={projectErrorMsg} showIcon closable onClose={()=>{setProjectError(false)}} style={{marginBottom:'20px'}} /> : ''}

        <Form form={projectform} layout="vertical" onFinish={submitNewProject} onValuesChange={onIncludeVersionChange}>
          
        <Form.Item
                name="projectId"
                hidden={true}
                >
                <Input />
            </Form.Item>
          <Form.Item
              name="projectName"
              label="项目名称"
              rules={[{ required: true, message: '请选择项目名称' }]}
          >
            <Input />
          </Form.Item>
          <Form.Item
              name="projectType"
              label="项目分类"
              rules={[{ required: true, message: '请选择项目名称' }]}
          >
            <Select >
              <Option selected value='1'>产品原型</Option>
              <Option value='2'>项目原型</Option>
            </Select>
          </Form.Item>
          <Form.Item
              name="description"
              label="项目说明"
              rules={[{ required: true, message: '请选输入项目说明' }]}
            >
              <TextArea allowClear={true} showCount={true} placeholder="项目说明" />
          </Form.Item>
          <Form.Item 
              name="includeVersion"
              label="同时上传原型"
              valuePropName="checked">
            <Checkbox />
          </Form.Item>
          <Form.Item
              hidden={!includeVersionFlag}
              name="localPath"
              label="原型本地目录"
              rules={[{ required: includeVersionFlag, message: '请选择原型本地目录' }]}
            >
            <Search  allowClear={true} placeholder="请选择目录" readOnly={true} onSearch={openFolder} enterButton='选择目录' />
          </Form.Item>
          <Form.Item
              hidden={!includeVersionFlag}
              name="changeLog"
              label="版本说明"
              rules={[{ required: includeVersionFlag, message: '请选输入版本说明' }]}
            >
              <TextArea allowClear={true} showCount={true} placeholder="版本说明" />
          </Form.Item>
        </Form>
    </Drawer>
    <Drawer title="系统配置"
        placement="right"
        width={300}
        closable={false}
        onClose={onConfigClose}
        visible={configVisible}
    footer={
      <div
        style={{
          textAlign: 'right',
        }}
      >
        <Button onClick={onConfigClose} style={{ marginRight: 8 }}>
          取消
        </Button>
        <Button onClick={()=>{configForm.submit()}} type="primary">
          保存配置
        </Button>
      </div>
    }
    ><ConfigForm form={configForm} closeHandler={onConfigClose}></ConfigForm></Drawer>
    </div>

  );
}
